package pers.cz.chat.filter;

import io.netty.channel.Channel;
import pers.cz.chat.GroupManager;
import pers.cz.netty.filter.FilterHandler;
import pers.cz.netty.filter.FilterHandlerContext;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.MsgType;

/**
 * @program: Jef-Chat
 * @description: 注册群聊拦截器
 * @author: Cheng Zhi
 * @create: 2025-02-01 15:26
 **/
public class CreateGroupFilter implements FilterHandler<Message, Channel> {

    @Override
    public boolean approve(Message message, Channel channel, FilterHandlerContext<Message, Channel> handlerContext) {

        if (message.getMsgType().equals(MsgType.CREATEGROUP)) {

            String groupInfo = (String) message.getAttachment("groupInfo");
            // 将群聊做为一个用户注册到用户管理中, 用户名为群组名，密码为群聊成员列表
            GroupManager.addGroup(message.getAttachment("groupName"), groupInfo);

            Message loginSuccessMessage = new Message();
            loginSuccessMessage.setMsgType(MsgType.CREATEGROUP);
            loginSuccessMessage.addAttachment("source", "server");
            loginSuccessMessage.addAttachment("result", "success");
            loginSuccessMessage.setContent("群聊创建登录成功！");
            channel.writeAndFlush(loginSuccessMessage);
            return true;
        }

        return handlerContext.doFilter(message, channel);
    }
}
